const Bookmark = require('../models/bookmark');
const Post = require('../models/post');

const bookmarkController = {
    async bookmarkPost(req, res, next) {
        try {
            const post = await Post.findById(req.params.post_id);
            if (!post) {
                return res.status(404).json({ error: 'Post not found' });
            }

            const { bookmark_id } = await Bookmark.create({
                user_id: req.user.user_id,
                post_id: req.params.post_id
            });
            res.status(201).json({ bookmark_id });
        } catch (error) {
            next(error);
        }
    },

    async unbookmarkPost(req, res, next) {
        try {
            await Bookmark.delete(req.user.user_id, req.params.post_id);
            res.json({ message: 'Post unbookmarked' });
        } catch (error) {
            next(error);
        }
    },

    async getBookmarks(req, res, next) {
        const { limit = 10, offset = 0 } = req.query;

        try {
            const bookmarks = await Bookmark.findByUserId(req.user.user_id, parseInt(limit), parseInt(offset));
            res.json(bookmarks);
        } catch (error) {
            next(error);
        }
    }
};

module.exports = bookmarkController;